package response

import (
	"math"
	"server/app/common/request"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// Pagination 结构体用于存储分页信息
type Pagination struct {
	TotalRecords int64 `json:"totalRecords"`
	TotalPages   int   `json:"totalPages"`
	CurrentPage  int   `json:"currentPage"`
	Limit        int   `json:"limit"`
}

// PaginatedResult 结构体用于存储带有分页信息的结果
type PaginatedResult struct {
	Pagination Pagination  `json:"pagination"`
	Records    interface{} `json:"records"`
}

// PaginateQuery 处理分页逻辑，返回分页信息和错误
func PaginateQuery(db *gorm.DB, page int, limit int) (pagination Pagination, err error) {
	var totalRecords int64
	err = db.Count(&totalRecords).Error
	if err != nil {
		return Pagination{}, err
	}

	totalPages := int(math.Ceil(float64(totalRecords) / float64(limit)))

	pagination = Pagination{
		TotalRecords: totalRecords,
		TotalPages:   totalPages,
		CurrentPage:  page,
		Limit:        limit,
	}

	return pagination, nil
}

// parsePagination 从请求中解析分页参数并设置到提供的分页结构体中。
func ParsePagination(ctx *gin.Context, page *request.Page) {
	if limit, err := strconv.ParseUint(ctx.DefaultQuery("limit", "10"), 10, 64); err == nil {
		page.Limit = limit
	} else {
		page.Limit = 10 // 默认值
	}

	if pageNum, err := strconv.ParseUint(ctx.DefaultQuery("page", "1"), 10, 64); err == nil {
		page.Page = pageNum
	} else {
		page.Page = 1 // 默认值
	}
}
